package com.lindroy.androidplayer.ui.officialaccount

import android.os.Bundle
import android.view.View
import com.lindroy.androidplayer.base.BaseListFragment
import com.lindroy.androidplayer.databinding.FragmentWxArticlesBinding
import com.lindroy.androidplayer.ui.adapter.WxArticleAdapter
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.collectListWhenResumed
import com.lindroy.androidplayer.utils.orZero
import com.lindroy.androidplayer.viewmodels.WxArticleViewModel

/**
 * @author Lin
 * @date 2022/1/22
 * @function 微信文章列表页面
 * @Description
 */
class WxArticlesFragment : BaseListFragment<FragmentWxArticlesBinding, WxArticleViewModel>() {

    private val chapterId by lazy { arguments?.getInt(KEY_ID).orZero() }

    private val adapter: WxArticleAdapter by lazy { WxArticleAdapter(viewLifecycleOwner) }

    companion object {
        private const val KEY_ID = "id"

        @JvmStatic
        fun create(id: Int) =
            WxArticlesFragment().apply {
                arguments = Bundle().apply {
                    putInt(KEY_ID, id)
                }
            }
    }

    override fun FragmentWxArticlesBinding.initView(savedInstanceState: Bundle?) {
        vm = mViewMode
        rvWxArticle.addSimpleDivider()
        rvWxArticle.adapter = adapter.withFooter()
    }

    override fun FragmentWxArticlesBinding.initListener() {
        mViewMode.setLayoutStateFlow(adapter.loadStateFlow)
        mViewMode.getWxArticles(chapterId).collectListWhenResumed(viewLifecycleOwner) {
            adapter.submitData(it)
        }
        mViewMode.itemClickLiveData.observe(viewLifecycleOwner) {
            WebViewFragment.start(this@WxArticlesFragment, it.id, it.link, it.title, it.collect)
        }
    }

    override fun initData() {}

    override fun onRefresh() {
        adapter.refresh()
    }

    override fun onRetry(view: View) {
        adapter.refresh()

    }
}